package com.woniu.rear.comm.core.util;

import java.util.Date;
import java.util.Map;

import javax.crypto.SecretKey;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.woniu.rear.comm.core.config.JwtConfig;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

/**
 * jwt模板类
 * @author liwei
 *
 */
@Component
public class JwtTemplate {
	
	@Autowired
	private JwtConfig jc;
	
	/**
	   *   由字符串生成secret;
	 * @return
	 */
	public SecretKey generalKey(){
    	SecretKey sk = Keys.hmacShaKeyFor(jc.getSecret().getBytes());
        return sk;
    }

	/**
	   *   生成Token
	 * @param maps
	 * @param subject
	 * @return
	 */
	public String createJwt(Map<String, Object> maps) {
		JwtBuilder jwtBuilder = Jwts.builder().signWith(generalKey(), SignatureAlgorithm.HS256);
		if(maps != null && maps.size() > 0) jwtBuilder.setClaims(maps);
		String token = jwtBuilder.setIssuedAt(new Date())
	                      .setExpiration(new Date(System.currentTimeMillis() + jc.getExpire() * 60 * 1000))
	                      .compact();
		return token;
	}
	
	/**
	   *   生成Token
	 * @param maps
	 * @param subject
	 * @return
	 */
	public String createJwt() {
		return createJwt(null);
	}
	
	/**
	   *   解析Token，获取注册信息
	 * @param jwt
	 * @return
	 */
	public Claims parseJwt(String token) {
		return Jwts.parserBuilder().setSigningKey(generalKey()).build().parseClaimsJws(token).getBody();
	} 

	/**
	   *   获取token失效时间
	 * @param token
	 * @return
	 * @throws Exception
	 */
    public Date getExpirationDateFromToken(String token) {
        return parseJwt(token).getExpiration();
    }

    /**
              *   验证token是否过期失效
     * @param token
     * @return
     * @throws Exception
     */
    public boolean isTokenExpired (String token) {
        Date expirationTime = getExpirationDateFromToken(token);
        return expirationTime.before(new Date());
    }

    /**
              *   获取jwt发布时间
     * @param token
     * @return
     * @throws Exception
     */
    public long getIssuedAtDateFromToken(String token){
        return parseJwt(token).getIssuedAt().getTime();
    }

}
